﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Examine;
using ProTrack.IServices.Plans;
using ProTrack.Utility;
using System.Threading.Tasks;
using System;
using System.Linq;
using System.Collections.Generic;
using ProTrack.Report;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 检验项目分类接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class QcProjectClassifyController : ControllerBase
    {
        public QcProjectClassifyController(IQcProjectClassifyServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }
        //接口
        public IQcProjectClassifyServices Services { get; }
        //系统日志收集辅助类
        public LogHelper LogHelper { get; }
        /// <summary>
        ///新增检验项目分类
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] QcProjectClassify model)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;

                var isSuccess = await Services.AddAsync(model);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据";
                }

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常,请稍后从试";
                await LogHelper.WriteErrorLog("检验项目分类-新增数据", ex, HttpContext);
            }
            return Ok(status);
        }
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("获取所有检验器具", ex, HttpContext);
            }

            return Ok(status);
        }
        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="ProjectCode"></param>
        /// <param name="ProjectName"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] string ProjectCode, [FromQuery] string ProjectName)
        {
            var status = BaseStatus.CreateInstance() ;
            try
            {
                ProjectCode = ProjectCode ?? "";
                ProjectName = ProjectName ?? "";
                var list = await Services.GetAsync(ProjectCode, ProjectName);

                //递归
                var dataList = TreeData(list);

                status.Count = dataList.Count;
                status.Data = dataList;
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("检测项目分类-获取树形数据", ex, HttpContext);
            }
            return Ok(status);
        }
        #region 数据递归处理
        private List<QcProjectClassifyDto> TreeData(IEnumerable<QcProjectClassify> list)
        {
            List<QcProjectClassifyDto> dataList = new List<QcProjectClassifyDto>();

            // 找到所有 父级
            var parent = list.Where(x => x.ParentClassify == 0);
            //查找所有子级
            var child = list.Where(x => x.ParentClassify != 0);
            foreach (var item in parent)
            {
                var model = new QcProjectClassifyDto
                {
                    Id = item.Id,
                    ProjectCode = item.ProjectCode,
                    ProjectName = item.ProjectName,
                    Classify = item.Classify,
                    Creator = item.Creator,
                    CreateTime = item.CreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                };
                dataList.Add(model);

                //判断当前父级是否存在子级
                var childList = list.Where(x => x.ParentClassify == item.Id).ToList();
                if (childList.Any())
                {
                    //存在子级
                    GetChild(childList, model, list.ToList());
                }
            }
            return dataList;
        }

        void GetChild(List<QcProjectClassify> child, QcProjectClassifyDto parent, List<QcProjectClassify> AllData)
        {
            //遍历所有子级
            foreach (var item in child)
            {
                var model = new QcProjectClassifyDto
                {
                    Id = item.Id,
                    ProjectCode = item.ProjectCode,
                    ProjectName = item.ProjectName,
                    Classify = item.Classify,
                    Creator = item.Creator,
                    ParentTypeName = parent.ProjectName,
                    ParentClassify = parent.Id,
                    CreateTime = item.CreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                };
                parent.Children.Add(model);

                //判断当前父级是否存在子级
                var childList = AllData.Where(x => x.ParentClassify == item.Id).ToList();
                if (childList.Any())
                {
                    //存在子级
                    GetChild(childList, model, AllData);
                }
            }
        }
        #endregion
        /*
         [HttpGet]
        public async Task<IActionResult> Get()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();

                status.Data = list;
                status.Count = list.Count();

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常,请稍后从试";
                //写日志
                await LogHelper.WriteErrorLog("检验项目分类-获取检验项目分类数据", ex, HttpContext);
            }
            return Ok(status);
        }
         */
        /// <summary>
        /// 修改检验项目分类
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] QcProjectClassify model)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model);
                if (isSuccess)
                {
                    status.Msg = "修改成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败,请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("检验项目分类" +
                    "-修改", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 批量删除设备
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("DelAlleeeel")]
        public async Task<IActionResult> DelAlleeeel([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败,请稍后重试 。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-批量删除设备", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 删除设备
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败,请稍后重试 。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("设备类型-删除设备", ex, HttpContext);
            }
            return Ok(status);
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {

                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[] {
                    new ReportDomain{ Title="序号",Fileld="No"},
                    new ReportDomain{ Title="检验项目分类编码",Fileld="ProjectCode"},
                    new ReportDomain{ Title="检验项目分类名称",Fileld="ProjectName"},
                    new ReportDomain{ Title="分类",Fileld="Classify"},
                    new ReportDomain{ Title="创建者",Fileld="Creator"},
                    new ReportDomain{ Title="创建时间",Fileld="CreateTime"},
                };
                var fileArray = BaseReport.Export(list, "检验项目分类信息", TitleArray);

                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "检验项目分类信息.xls");
            }
            catch (Exception ex)
            {

                //此处应当日志记录
                await LogHelper.WriteErrorLog("检验项目分类-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }
        }
    }
}
